from dash import Input, Output, State, callback_context, html, dcc, ALL # 引入 ALL
from models import db, RepairRecord, Organization, Department, Product # 确保导入所需模型
import dash_bootstrap_components as dbc # 引入 dbc
import dash


# 新增报修Modal组件
def create_new_repair_modal():
    """创建新增报修的Modal组件"""
    return dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("新增报修", style=title_style), close_button=True),
            dbc.ModalBody([
                dbc.Form([
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("所属机构", html_for="new-repair-org"),
                            dcc.Dropdown(
                                id="new-repair-org",
                                options=[],
                                placeholder="请选择机构",
                                className="mb-3"
                            ),
                        ], width=3),
                        dbc.Col([
                            dbc.Label("所属科室", html_for="new-repair-dept"),
                            dcc.Dropdown(
                                id="new-repair-dept",
                                options=[],
                                placeholder="请先选择机构",
                                className="mb-3",
                                disabled=True
                            ),
                        ], width=3),
                        dbc.Col([
                            dbc.Label("设备名称", html_for="new-repair-device"),
                            dcc.Dropdown(
                                id="new-repair-device",
                                options=[],
                                placeholder="请先选择科室",
                                className="mb-3",
                                disabled=True
                            ),
                        ], width=3),
                        dbc.Col([
                            dbc.Label("叫修人姓名", html_for="new-repair-caller"),
                            dbc.Input(
                                type="text",
                                id="new-repair-caller",
                                placeholder="请输入叫修人姓名",
                                className="mb-3"
                            ),
                        ], width=3),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("故障现象", html_for="new-repair-fault"),
                            dbc.Textarea(
                                id="new-repair-fault",
                                placeholder="请描述故障现象",
                                style={"height": "100px"},
                                className="mb-3"
                            ),
                        ], width=12),
                    ]),
                    dbc.Alert(id="new-repair-alert", color="danger", is_open=False, duration=4000),
                ]),
            ]),
            dbc.ModalFooter([
                dbc.Button("放弃", id="new-repair-cancel", className="me-2", color="secondary"),
                dbc.Button("提交", id="new-repair-confirm", color="primary"),
            ]),
        ],
        id="new-repair-modal",
        is_open=False,
        size="lg",
        backdrop="static",
        centered=True,
        scrollable=True,
        style={"marginTop": "120px"}
    )

# 注册Modal相关的回调函数
def register_modal_callbacks(dash_app):
    """注册与Modal相关的回调函数"""
    from dash import Input, Output
    from models import Department

    def register_filter_callbacks(app):
        @app.callback(
            Output("filter-dept", "options"),
            Output("filter-dept", "value"),
            Input("filter-org", "value"),
        )
        def update_dept_options(selected_org):
            if selected_org:
                # 查询该机构下的所有科室
                depts = Department.query.filter_by(org_name=selected_org, is_active=True).all()
                options = [{"label": d.dept_name, "value": d.dept_name} for d in depts]
                # 默认不选中任何科室
                return options, None
            # 没选机构时，科室下拉为空
            return [], None

    # --- 新增：控制新增报修Modal的显示与隐藏 ---
    @dash_app.callback(
        Output("new-repair-modal", "is_open"),
        Output("new-repair-alert", "is_open", allow_duplicate=True), # 清空提示
        Output("new-repair-alert", "children", allow_duplicate=True), # 清空提示内容
        # 清空表单字段
        Output("new-repair-org", "value", allow_duplicate=True),
        Output("new-repair-dept", "value", allow_duplicate=True),
        Output("new-repair-device", "value", allow_duplicate=True),
        Output("new-repair-fault", "value", allow_duplicate=True),
        Output("new-repair-caller", "value", allow_duplicate=True),
        Output("new-repair-dept", "disabled", allow_duplicate=True),
        Output("new-repair-device", "disabled", allow_duplicate=True),
        [Input("new-repair-btn", "n_clicks"),
         Input("new-repair-cancel", "n_clicks"),
         Input("new-repair-confirm", "n_clicks")], # 监听确认按钮
        [State("new-repair-modal", "is_open")],
        prevent_initial_call=True
    )
    def toggle_new_repair_modal(n_open, n_cancel, n_confirm, is_open):
        ctx = dash.callback_context
        triggered_id = ctx.triggered_id
        print(f"--- toggle_new_repair_modal triggered by: {triggered_id} ---") # 添加打印语句

        if not triggered_id:
             print("No trigger ID found.")
             return is_open, False, "", None, None, None, "", "", True, True

        if triggered_id == "new-repair-btn":
            print("Opening new-repair-modal.")
            # 打开时清空表单并重置状态
            return True, False, "", None, None, None, "", "", True, True
        elif triggered_id == "new-repair-cancel":
            print("Closing new-repair-modal via Cancel.")
            # 取消时关闭
            return False, False, "", None, None, None, "", "", True, True
        elif triggered_id == "new-repair-confirm":
            print("Confirm button clicked, modal close handled by submit callback.")
            # 确认按钮由 submit_new_repair 回调处理关闭逻辑，这里不处理
            return dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update

        print("No relevant trigger, returning current state.")
        return is_open, False, "", dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update


def create_repair_respond_modal():
    """创建维修响应的Modal组件"""
    return dbc.Modal(
        [
            dbc.ModalHeader(
                dbc.ModalTitle("维修响应", style={"fontWeight": "bold", "color": "#2c3e50"}), 
                close_button=True,
                style={"borderBottom": "2px solid #3498db", "backgroundColor": "#f8f9fa"}
            ),
            dbc.ModalBody([
                # 维修信息展示区
                html.Div(
                    id="repair-respond-info", 
                    style={
                        "marginBottom": "20px",
                        "padding": "15px",
                        "backgroundColor": "#f8f9fa",
                        "borderRadius": "8px",
                        "border": "1px solid #e9ecef",
                        "boxShadow": "0 2px 4px rgba(0,0,0,0.1)"
                    }
                ),
                dbc.Form([
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修人员", html_for="repair-respond-person", className="form-label fw-bold", style={"color": "#495057"}),
                            dbc.Input(
                                type="text",
                                id="repair-respond-person",
                                placeholder="请输入维修人员",
                                className="form-control",
                                style={
                                    "borderRadius": "6px", 
                                    "border": "1px solid #ced4da",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=4, className="mb-3"),
                        dbc.Col([
                            dbc.Label("维修公司", html_for="repair-respond-company", className="form-label fw-bold", style={"color": "#495057"}),
                            dbc.Input(
                                type="text",
                                id="repair-respond-company",
                                placeholder="请输入维修公司",
                                className="form-control",
                                style={
                                    "borderRadius": "6px", 
                                    "border": "1px solid #ced4da",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=4, className="mb-3"),
                    ], className="mb-2"),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修类型", html_for="repair-respond-repairtype", className="form-label fw-bold", style={"color": "#495057"}),
                            dbc.Input(
                                type="text",
                                id="repair-respond-repairtype",
                                placeholder="请输入维修类型",
                                className="form-control",
                                style={
                                    "borderRadius": "6px", 
                                    "border": "1px solid #ced4da",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=4, className="mb-3"),
                        dbc.Col([
                            dbc.Label("预计完成日期", html_for="repair-respond-expected-date", className="form-label fw-bold", style={"color": "#495057","display": "none",}),
                            dcc.DatePickerSingle(
                                id="repair-respond-expected-date",
                                placeholder="请选择预计完成日期",
                                className="form-control",
                                display_format="YYYY-MM-DD",
                                style={
                                    "display": "none",
                                    "width": "100%", 
                                    "borderRadius": "6px",
                                    "fontSize": "14px",
                                    "border": "1px solid #ced4da",
                                    "padding": "10px 12px",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=4, className="mb-3"),
                    ], className="mb-2"),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("备注", html_for="repair-respond-remarks", className="form-label fw-bold", style={"display": "none","color": "#495057"}),
                            dbc.Textarea(
                               
                                id="repair-respond-remarks",
                                placeholder="请输入备注",
                                className="form-control",
                                style={
                                    "display": "none",
                                    "height": "20px",
                                    "borderRadius": "6px",
                                    "border": "1px solid #ced4da",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "resize": "vertical",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=4, className="mb-3"),
                    ]),
                    dbc.Alert(
                        id="repair-respond-alert", 
                        color="danger", 
                        is_open=False, 
                        duration=4000,
                        style={
                            "marginTop": "15px",
                            "borderRadius": "6px",
                            "border": "none"
                        }
                    ),
                ], className="p-4", style={"backgroundColor": "#ffffff", "borderRadius": "8px"}),
            ], style={"padding": "20px", "backgroundColor": "#f8f9fa"}),
            dbc.ModalFooter([
                dbc.Button(
                    "放弃", 
                    id="repair-respond-cancel", 
                    className="me-3", 
                    color="secondary",
                    style={
                        "borderRadius": "6px", 
                        "padding": "10px 20px",
                        "fontWeight": "500",
                        "border": "none",
                        "boxShadow": "0 2px 4px rgba(0,0,0,0.1)"
                    }
                ),
                dbc.Button(
                    "提交", 
                    id="repair-respond-confirm", 
                    color="primary",
                    style={
                        "borderRadius": "6px", 
                        "padding": "10px 20px",
                        "fontWeight": "500",
                        "border": "none",
                        "backgroundColor": "#3498db",
                        "boxShadow": "0 2px 4px rgba(52, 152, 219, 0.3)"
                    }
                ),
            ], style={
                "borderTop": "1px solid #e9ecef", 
                "padding": "15px 20px",
                "backgroundColor": "#f8f9fa",
                "justifyContent": "flex-end"
            }),
        ],
        id="repair-respond-modal",
        is_open=False,
        size="lg",
        backdrop="static",
        centered=True,
        scrollable=True,
        style={
            "marginTop": "120px",
            "boxShadow": "0 10px 30px rgba(0,0,0,0.2)",
            "border": "none",
            "borderRadius": "12px",
            # "overflow": "hidden"
        }
    )


def create_repair_complete_modal():
    return dbc.Modal(
        [
            dbc.ModalHeader(
                dbc.ModalTitle("维修完成", style={"fontWeight": "bold", "color": "#ffffff"}), 
                close_button=True,
                style={"borderBottom": "2px solid #3498db", "backgroundColor": "#3498db"}
            ),
            dbc.ModalBody([
                # 维修信息展示区
                html.Div(
                    id="repair-complete-info", 
                    style={
                        "marginBottom": "20px",
                        "padding": "15px",
                        "backgroundColor": "#1976d2",
                        "borderRadius": "8px",
                        "border": "1px solid #e9ecef",
                        "boxShadow": "0 2px 4px rgba(0,0,0,0.1)"
                    }
                ),
                dbc.Form([
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修内容", html_for="repair-complete-content", className="form-label fw-bold", style={"color": "#ffffff"}),
                            dbc.Textarea(
                                id="repair-complete-content",
                                placeholder="请输入维修内容，指具体工作",
                                className="form-control",
                                style={
                                    "height": "20px", 
                                    "width": "400px",  # 修改为400px
                                    "borderRadius": "6px",
                                    "border": "1px solid #64b5f6",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "resize": "vertical",
                                    "backgroundColor": "#2196f3",
                                    "color": "#ffffff",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=6, className="mb-3"),
                    ]),
                    # 添加维修类型输入框
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修类型", html_for="repair-type", className="form-label fw-bold", style={"color": "#ffffff"}),
                            dbc.Input(
                                type="text",
                                id="repair-type",
                                placeholder="请输入维修类型，如电路、水路、结构",
                                className="form-control",
                                style={
                                    "width": "400px",  # 设置为400px
                                    "borderRadius": "6px", 
                                    "border": "1px solid #64b5f6",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "backgroundColor": "#2196f3",
                                    "color": "#ffffff",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=6, className="mb-3"),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修结果", html_for="repair-complete-result", className="form-label fw-bold", style={"color": "#ffffff"}),
                            dbc.Input(
                                type="text",
                                id="repair-complete-result",
                                placeholder="请输入维修结果：如修复完成、修复失败",
                                className="form-control",
                                style={
                                    "width": "400px",  # 修改为400px
                                    "borderRadius": "6px", 
                                    "border": "1px solid #64b5f6",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "backgroundColor": "#2196f3",
                                    "color": "#ffffff",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=6, className="mb-3"),
                        dbc.Col([
                            dbc.Label("维修费用", html_for="repair-complete-cost", className="form-label fw-bold", style={"color": "#ffffff"}),
                            dbc.Input(
                                type="number",
                                id="repair-complete-cost",
                                placeholder="请输入维修费用，不输则默认为0",
                                className="form-control",
                                style={
                                    "width": "400px",  # 修改为400px
                                    "borderRadius": "6px", 
                                    "border": "1px solid #64b5f6",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "backgroundColor": "#2196f3",
                                    "color": "#ffffff",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=6, className="mb-3"),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("更换配件", html_for="repair-complete-parts", className="form-label fw-bold", style={"color": "#ffffff"}),
                            dbc.Textarea(
                                id="repair-complete-parts",
                                placeholder="请输入更换配件信息",
                                className="form-control",
                                style={
                                    "height": "20px",
                                    "width": "400px",  # 修改为400px
                                    "borderRadius": "6px",
                                    "border": "1px solid #64b5f6",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "resize": "vertical",
                                    "backgroundColor": "#2196f3",
                                    "color": "#ffffff",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=6, className="mb-3"),
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("维修备注", html_for="repair-complete-remarks", className="form-label fw-bold", style={"color": "#ffffff"}),
                            dbc.Textarea(
                                id="repair-complete-remarks",
                                placeholder="请输入备注",
                                className="form-control",
                                style={
                                    "width": "400px",  # 修改为400px
                                    "height": "20px",
                                    "borderRadius": "6px",
                                    "border": "1px solid #64b5f6",
                                    "padding": "10px 12px",
                                    "fontSize": "14px",
                                    "resize": "vertical",
                                    "backgroundColor": "#2196f3",
                                    "color": "#ffffff",
                                    "transition": "border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out"
                                }
                            ),
                        ], width=6, className="mb-3"),
                    ]),
                    dbc.Alert(
                        id="repair-complete-alert", 
                        color="danger", 
                        is_open=False, 
                        duration=4000,
                        style={
                            "marginTop": "15px",
                            "borderRadius": "6px",
                            "border": "none",
                            "backgroundColor": "#ffcdd2",
                            "color": "#d32f2f"
                        }
                    ),
                ], className="p-4", style={"backgroundColor": "#1976d2", "borderRadius": "8px"}),
            ], style={"padding": "20px", "backgroundColor": "#e3f2fd"}),
            dbc.ModalFooter([
                dbc.Button(
                    "放弃", 
                    id="repair-complete-cancel", 
                    className="me-3", 
                    color="secondary",
                    style={
                        "borderRadius": "6px", 
                        "padding": "10px 20px",
                        "fontWeight": "500",
                        "border": "none",
                        "boxShadow": "0 2px 4px rgba(0,0,0,0.1)",
                        "backgroundColor": "#90caf9",
                        "color": "#1a237e"
                    }
                ),
                dbc.Button(
                    "提交", 
                    id="repair-complete-confirm", 
                    color="primary",
                    style={
                        "borderRadius": "6px", 
                        "padding": "10px 20px",
                        "fontWeight": "500",
                        "border": "none",
                        "backgroundColor": "#1565c0",
                        "boxShadow": "0 2px 4px rgba(21, 101, 192, 0.3)",
                        "color": "#ffffff"
                    }
                ),
            ], style={
                "borderTop": "1px solid #bbdefb", 
                "padding": "15px 20px",
                "backgroundColor": "#e3f2fd",
                "justifyContent": "flex-end"
            }),
        ],
        id="repair-complete-modal",
        is_open=False,
        size="lg",
        backdrop="static",
        centered=True,
        scrollable=True,
        style={
            "marginTop": "120px",
            "boxShadow": "0 10px 30px rgba(0,0,0,0.2)",
            "border": "none",
            "borderRadius": "12px",
            "overflow": "hidden"
        }
    )


def create_upload_proof_modal():
    return dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("上传工单图片"), close_button=True),
            dbc.ModalBody(
                html.Div([
                    # 横向flex布局容器
                    html.Div([
                        # 左侧上传区
                        html.Div([
                            dcc.Upload(
                                id="upload-proof",
                                children=html.Div([
                                    "拖拽或点击选择图片上传"
                                ]),
                                style={
                                    "width": "100%", "height": "100px", "lineHeight": "100px",
                                    "borderWidth": "1px", "borderStyle": "dashed",
                                    "borderRadius": "5px", "textAlign": "center", "margin": "100px 0"
                                },
                                multiple=False
                            ),
                            # dbc.Alert(id="upload-proof-alert", color="info", is_open=False, duration=4000),
                            dbc.Alert(id="upload-proof-alert", color="info", is_open=False, style={"height": "40px"}),
                        ], style={"width": "30%", "minWidth": "200px", "paddingRight": "16px", "marginTop": "32px","flex": "1",
                                }), 
                        # 右侧预览区
                        html.Div(
                            id="proof-preview-area",
                            style={"width": "70%", "minWidth": "550px","maxWidth": "950px", "display": "flex", "alignItems": "center"}
                        ),
                        dcc.Store(id="proof-preview-refresh"), # 用于刷新预览
                    ], style={"display": "flex", "flexDirection": "row", "width": "100%"})
                ])
            ),
            dbc.ModalFooter([
                dbc.Button("关闭", id="upload-proof-cancel", color="secondary"),
            ]),
        ],
        id="upload-proof-modal-2",
        is_open=False,
        size="lg",
        # id={"type": "upload-proof-modal", "index": 0},  # 唯一id定义
        # is_open=False,
        # size="lg",
        centered=True,
        scrollable=True
    )


# 统一样式变量
modal_style = {
    "backgroundColor": "#3498db",
    "border": "none",
    "borderRadius": "12px",
    "boxShadow": "0 10px 30px rgba(255,255,255,0.2)"
}

header_style = {
    "backgroundColor": "#2980b9",
    "borderBottom": "2px solid #ffffff"
}

title_style = {
    "color": "#ffffff",
    "fontWeight": "600",
    "fontSize": "20px"
}

# 在create_repair_respond_modal和create_repair_complete_modal中应用相同变量
input_style = {
    "backgroundColor": "rgba(255,255,255,0.1)",
    "border": "1px solid #64b5f6",
    "color": "#ffffff",
    "borderRadius": "8px",
    "padding": "12px 16px",
    "::placeholder": {"color": "#e0e0e0"}
}

# 应用到所有dbc.Input和dbc.Textarea